import { OAuth2Client } from 'google-auth-library'
import type { GoogleUserInfo } from './authService'

export class GoogleAuthService {
  private static client: OAuth2Client

  // 初始化Google OAuth客户端
  static initialize() {
    const clientId = process.env.GOOGLE_CLIENT_ID
    const clientSecret = process.env.GOOGLE_CLIENT_SECRET
    
    if (!clientId || !clientSecret) {
      console.warn('Google OAuth credentials not configured')
      return
    }

    this.client = new OAuth2Client(clientId, clientSecret)
  }

  /**
   * 验证Google ID Token并获取用户信息
   */
  static async verifyGoogleToken(idToken: string): Promise<GoogleUserInfo> {
    if (!this.client) {
      throw new Error('Google OAuth not configured')
    }

    try {
      const ticket = await this.client.verifyIdToken({
        idToken,
        audience: process.env.GOOGLE_CLIENT_ID,
      })

      const payload = ticket.getPayload()
      if (!payload) {
        throw new Error('Invalid Google token payload')
      }

      // 提取用户信息
      const googleUserInfo: GoogleUserInfo = {
        googleId: payload.sub,
        email: payload.email || '',
        username: payload.name || payload.email?.split('@')[0] || 'user',
        avatar: payload.picture
      }

      // 验证必要字段
      if (!googleUserInfo.googleId || !googleUserInfo.email) {
        throw new Error('Missing required user information from Google')
      }

      return googleUserInfo
    } catch (error) {
      console.error('Google token verification failed:', error)
      throw new Error('Invalid Google token')
    }
  }

  /**
   * 生成Google OAuth授权URL
   */
  static generateAuthUrl(redirectUri: string): string {
    if (!this.client) {
      throw new Error('Google OAuth not configured')
    }

    return this.client.generateAuthUrl({
      access_type: 'offline',
      scope: [
        'https://www.googleapis.com/auth/userinfo.profile',
        'https://www.googleapis.com/auth/userinfo.email'
      ],
      redirect_uri: redirectUri,
    })
  }

  /**
   * 使用授权码获取访问令牌
   */
  static async getTokensFromCode(code: string, redirectUri: string) {
    if (!this.client) {
      throw new Error('Google OAuth not configured')
    }

    try {
      const { tokens } = await this.client.getToken({
        code,
        redirect_uri: redirectUri,
      })

      return tokens
    } catch (error) {
      console.error('Failed to exchange code for tokens:', error)
      throw new Error('Failed to get Google tokens')
    }
  }

  /**
   * 使用访问令牌获取用户信息
   */
  static async getUserInfoFromTokens(accessToken: string): Promise<GoogleUserInfo> {
    try {
      const response = await fetch('https://www.googleapis.com/oauth2/v2/userinfo', {
        headers: {
          Authorization: `Bearer ${accessToken}`,
        },
      })

      if (!response.ok) {
        throw new Error('Failed to fetch user info from Google')
      }

      const userInfo = await response.json()

      return {
        googleId: userInfo.id,
        email: userInfo.email,
        username: userInfo.name || userInfo.email?.split('@')[0] || 'user',
        avatar: userInfo.picture
      }
    } catch (error) {
      console.error('Failed to get user info from Google:', error)
      throw new Error('Failed to get user information')
    }
  }

  /**
   * 检查Google OAuth是否已配置
   */
  static isConfigured(): boolean {
    return !!process.env.GOOGLE_CLIENT_ID && !!process.env.GOOGLE_CLIENT_SECRET
  }
}

// 初始化Google OAuth服务
GoogleAuthService.initialize()
